package com.caojin.propertyInjector.propertyResolver;

import java.util.Properties;
import com.caojin.propertyInjector.annotation.FileType;
import com.caojin.util.PropertiesUtil;

public class PropertiesResolerFactoy {
	// 默认的配置文件类型与文件解析器的映射文件
	public static final String DEFAULT_CONFIGURATION = "/propResolvers.cfg";
	private String configuration = DEFAULT_CONFIGURATION;
	private Properties props;

	public PropertiesResolerFactoy() {
		initConfiguration();
	}

	public PropertiesResolerFactoy(String configuration) {
		this.configuration = configuration;
		initConfiguration();
	}

	public PropertiesResolver getInstance() {
		return getInstance(FileType.PROPERTIES);
	}

	// 根据文件类型获取对应的解析器
	@SuppressWarnings("rawtypes")
	public PropertiesResolver getInstance(String fileType) {
		String className = props.getProperty(fileType);
		if (className == null || className.equals("")) {
			throw new RuntimeException("can't find resolver for files of \""
					+ fileType + "\" type");
		}
		Class cls = null;
		try {
			cls = Class.forName(className);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		Object obj = null;
		try {
			obj = cls.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		if (!PropertiesResolver.class.isInstance(obj)) {
			throw new RuntimeException(className
					+ " must extend PropertiesResolver");
		}
		return (PropertiesResolver) obj;
	}

	// 初始化文件类型与解析器的对应关系
	private void initConfiguration() {
		try {
			props = PropertiesUtil.loadProperties(configuration);
		} catch (Exception e) {
			System.out
					.print(e.getMessage()
							+ " use default property resolver : BasePropertiesResolver");
		}
		if (props == null) {
			props = new Properties();
			// 使用默认的配置文件解析器
			props.put(FileType.PROPERTIES.toString(),
					"com.caojin.propertyInjector.propertyResolver.BasePropertiesResolver");
		}
	}
}
